package top.likeqc.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/** 链接: <a href="https://leetcode.cn/problems/4sum ">leetcode题库</a> */
public class FourSum {
    public static void main(String[] args) {
        Solution solution = new FourSum().new Solution();

        // solution.fourSum(new int[]{1,0,-1,0,-2,2}, 0);
        solution.fourSum(
                new int[] {0, 0, 0, 1000000000, 1000000000, 1000000000, 1000000000}, 1000000000);
    }
    // leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> ans = new ArrayList<>();
            Arrays.sort(nums);
            int n = nums.length;
            // 1.遍历第1、2位数字（每层遍历跳过与上一次遍历相同的重复值）
            // 2.使用双指针找出第3、4位数字
            // 3.注意 int 数值范围
            for (int i = 0; i < n - 3; i++) {
                if (i > 0 && nums[i - 1] == nums[i]) {
                    continue;
                }
                if ((long) nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                    continue;
                }
                if ((long) nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target) {
                    continue;
                }

                for (int j = i + 1; j < n - 2; j++) {
                    if (j > i + 1 && nums[j - 1] == nums[j]) {
                        continue;
                    }

                    int left = j + 1, right = n - 1;
                    while (left < right) {
                        if (left != j + 1 && nums[left] == nums[left - 1]) {
                            left++;
                            continue;
                        }
                        if (right != n - 1 && nums[right] == nums[right + 1]) {
                            right--;
                            continue;
                        }

                        long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
                        if (sum < target) {
                            left++;
                        } else if (sum > target) {
                            right--;
                        } else {
                            ArrayList<Integer> list = new ArrayList<>();
                            list.add(nums[i]);
                            list.add(nums[j]);
                            list.add(nums[left]);
                            list.add(nums[right]);
                            ans.add(list);

                            left++;
                        }
                    }
                }
            }
            return ans;
        }
    }
    // leetcode submit region end(Prohibit modification and deletion)

}
